package com.nurt.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import jakarta.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ServletHelper {
    public static <T> T getRequestBodyAsObject(HttpServletRequest request, Class<T> clazz) throws IOException {
        // 从请求中获取 JSON 数据
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        // 使用 Fastjson 将 JSON 数据转换为指定的 Java 对象
        return JSON.parseObject(sb.toString(), clazz);
    }
    
    public static JSONObject getRequestBodyAsJson(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return JSON.parseObject(sb.toString());
    }
}
